package day09;


import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;

import day09.bean.Request;
import day09.bean.Respons;
import day09.bean.UserResult;

/**
 * 发布服务的
 */
public class Server {
    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(9999);
            while(true){
                //建立连接
                Socket accept = serverSocket.accept();
                Respons respons = new Respons();
                ObjectInputStream objectInputStream = new ObjectInputStream(accept.getInputStream());
                //接受到客户端请的数据
                Request req = (Request)objectInputStream.readObject();
                String className = req.getClassName();
                String methodName = req.getMethod();
                Class[] valueType = req.getValueType();
                Object[] value = req.getValue();
                ObjectOutputStream objectOutputStream = new ObjectOutputStream(accept.getOutputStream());
                try{
                    //使用反射进行执行相应的方法
                    Class<?> forName = Class.forName(className);
                    Object instance = forName.newInstance();
                    Method method = forName.getMethod(methodName, valueType);
                    UserResult result = (UserResult)method.invoke(instance, value);

                    //发送返回结果
                    System.out.println(result);
                    respons.setResult(result);
                    respons.setStatus("200");

                    objectOutputStream.writeObject(respons);
                    objectOutputStream.flush();
                }catch (Exception e){
                    respons.setStatus("500");//服务器内部出问题
                    objectOutputStream.writeObject(respons);
                    objectOutputStream.flush();
                }finally {
                    accept.shutdownInput();
                    accept.shutdownOutput();
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
